"""历史日志"""

import math
from src.db import dbm, dbs
from src.core.variables.status import *
from src.core.variables.constant import BLOCK_SIZE


def java(schema):
    """java app历史日志，根据块的数值区分加载行数"""
    with dbm.get("hosting_Java") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        result = []
        db_result = (
            db_session.query(dbs.hosting_Java.App_backup)
            .filter(dbs.hosting_Java.App_backup.back_id == schema.back_id)
            .first()
        )
        if db_result:
            with open(db_result.log_path, "r", encoding="utf-8") as file:
                context = file.readlines()
                start = schema.line * -BLOCK_SIZE
                end = start + BLOCK_SIZE
                result = context[start, end]
        return SUCCESS_CODE_CUSTOMIZE(result, 200)


def java_line_num(schema):
    """
    java app历史日志块数量
    1块=300行
    """
    with dbm.get("hosting_Java") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        result = []
        db_result = (
            db_session.query(dbs.hosting_Java.App_backup)
            .filter(dbs.hosting_Java.App_backup.back_id == schema.back_id)
            .first()
        )
        if db_result:
            with open(db_result.log_path, "r", encoding="utf-8") as file:
                context = file.readlines()
                # 结果向上取整
                return SUCCESS_CODE_CUSTOMIZE(math.ceil(len(context) / BLOCK_SIZE), 200)
        return SUCCESS_CODE_CUSTOMIZE(result, 200)


def java_list(schema):
    """java app历史日志列表"""
    with dbm.get("hosting_Java") as db_session:
        from sqlalchemy.orm import scoped_session
        db_session: scoped_session
        result = []
        db_result = db_session.query(
            dbs.hosting_Java.App_backup.app_id == schema.app_id
        ).all()
        for record in db_result:
            result.append(
                {
                    "back_id": record.back_id,
                    "app_id": record.app_id,
                    "alias": record.alias,
                    "deploy_time": record.deploy_time,
                    "log_path": record.log_path,
                    "notes": record.notes,
                    "version": record.version,
                    "time_dir": record.time_dir,
                }
            )
        return SUCCESS_CODE_CUSTOMIZE(result, 200)
